import { defineStore } from "pinia";
import { api_user_login, api_get_user_info } from "@/service/api/login";
import { showNotify } from "vant";

export const use_user_store = defineStore("user_store", {
  state: (): any => {
    return {
      token: JSON.parse(localStorage.getItem("token")),
      user_info: JSON.parse(localStorage.getItem("user_info")),
    };
  },
  actions: {
    set_token(data: string) {
      this.token = data;
      localStorage.setItem("token", JSON.stringify(data));
    },
    set_userdata(data: any) {
      this.user_info = data;
      localStorage.setItem("user_info", JSON.stringify(data));
    },
    // 用户登录
    async user_login(params: user_account) {
      let res: any = await api_user_login(params);
      if (!!res.result) {
        this.set_token(res.result.token);
        this.set_userdata(res.result);
        showNotify({
          type: "success",
          message: "登录成功,欢迎您!",
        });
        return true;
      } else {
        throw new Error("登录失败");
        return false;
      }
    },
    // 获取用户信息
    async get_user_info() {
      let res: any = await api_get_user_info();
      if (!!res.result) {
        this.set_token(res.result.token);
        this.set_userdata(res.result);
        return true;
      } else {
        this.user_logout();
        // throw new Error("登录失败");
        return false;
      }
    },

    //   用户登出
    user_logout() {
      localStorage.clear();
      this.$reset();
    },
  },
});

interface user_account {
  name?: string;
  password: string;
  phone: string;
  project_id: number;
}
